//
//  ProductDisplayDetailVC.m
//  KuWoCan
//
//  Created by hwd on 17/4/11.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ProductDisplayDetailVC.h"
#import "DoubleLabCell.h"
#import "BottomDoubleBtnView.h"
#import "NWSaleApplyRequest.h"
#import "PDDetailModel.h"
#import "CargoCell.h"
#import "PhotoManageCell.h"
#import "NWPicManageRequest.h"
#import "PicPageListModel.h"
#import "PDCommitVC.h"
#import "AFNetworking.h"
#import "OrderRecordTableViewCell.h"

@interface ProductDisplayDetailVC ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    dispatch_semaphore_t semaphore;
    //拒绝  通过
    BottomDoubleBtnView *btnsView;
}

@property (nonatomic,strong) NSArray *detailInfoArr; //活动详情

@property (nonatomic,strong) NSMutableArray *cargoListArr;  //商品数组

@property (nonatomic,copy)NSArray<OrderDetailCheckModel *> *recordListArr; //审批信息数组

@property (nonatomic,strong) ProductDisplayListModel *detailInfoModel;

@property (nonatomic,strong) UITableView *tabView;

@property (nonatomic,strong) UIAlertView *deleteAlert;

@property (nonatomic,strong) NSMutableDictionary *picsDic; //图片数组

@property (nonatomic,assign) SAQueryStatus orderStatus;

@property (nonatomic,assign)BOOL isNeedHXBZ;//是否需要核销标准
@property (nonatomic,assign)BOOL isShowHXBZ;//是否展示核销标准
@property (nonatomic,strong)NSMutableArray *DataHXBZArr;//核销标准数组
@property (nonatomic,assign)NSInteger tagNumber;//核销标准按钮点击tag值
@property (nonatomic,strong)NSString *mbContect;//核销标准的内容
@property (nonatomic,strong)UIButton *deleteBtn;

@end

@implementation ProductDisplayDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.moduleType == HomeModuleTypePA) {
        self.title = @"产品陈列费用申请";
    } else {
        self.title = @"产品陈列费用核销";
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)startRequestTable
{
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    if (_moduleType == HomeModuleTypePA)
    {
        [request startRequestProductApplyDetailWithId:_orderId];
    }
    else
    {
        [request startRequestProductCheckDetailWithId:_orderId];
    }
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            //这里做数据解析
            PDDetailModel *model = [[PDDetailModel alloc] initWithDictionary:result error:nil];
            if (_moduleType == HomeModuleTypePA)
            {
//                _detailInfoModel = [[ProductDisplayListModel alloc] initWithDictionary:result[@"kwDisplayApplication"] error:nil];
                _detailInfoModel = model.kwDisplayApplication;
            }
            else
            {
                _detailInfoModel = [[ProductDisplayListModel alloc] initWithDictionary:result[@"kwDisplayExamine"] error:nil];
            }
            self.recordListArr = model.recordList;
            _cargoListArr = [SADetailCargoModel arrayOfModelsFromDictionaries:model.itemList];
            
            _detailInfoArr = @[
                               @[
                                   @{@"陈列活动名称":[ToolViewViewController GetDataStr:_detailInfoModel.name]},
                                   @{@"促销目的":[ToolViewViewController GetDataStr:_detailInfoModel.objective]},
                                   @{@"执行城市":[ToolViewViewController GetDataStr:_detailInfoModel.city]},
                                   @{@"执行范围":[ToolViewViewController GetDataStr:_detailInfoModel.ranges]},
                                   @{@"执行时间":[ToolViewViewController GetDataStr:_detailInfoModel.executionTime]},
                                   @{@"销售额":[ToolViewViewController GetDataStr:_detailInfoModel.salesVolume]},
                                   @{@"费效比率":[ToolViewViewController GetDataStr:_detailInfoModel.ratio]},
                                   @{@"期间销售额" : [ToolViewViewController GetDataStr:_detailInfoModel.activitySales]},
                                   @{@"期间费效比率" :[ToolViewViewController GetDataStr:_detailInfoModel.activityRatio]}
                                   ],
                                @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.shelfNumber]},
                                   @{@"面积": [ToolViewViewController GetDataStr:_detailInfoModel.shelfArea]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.shelfDescription]},
                                   @{@"费用预算":  [ToolViewViewController GetDataStr:_detailInfoModel.shelfBudget]}
                                   ],
                                @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.stackingNumber]},
                                   @{@"形式": [ToolViewViewController GetDataStr:_detailInfoModel.stackingForm]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.stackingArea]},
                                   @{@"费用预算": [ToolViewViewController GetDataStr:_detailInfoModel.stackingBudget]}
                                   ],
                                @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.otherNumber]},
                                   @{@"形式": [ToolViewViewController GetDataStr:_detailInfoModel.otherForm]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.otherArea]},
                                   @{@"费用预算": [ToolViewViewController GetDataStr:_detailInfoModel.otherBudget]}
                                   ]
                               ];
            
            if (_moduleType == HomeModuleTypePA)
            {
                _orderStatus = [_detailInfoModel.approvalStatus integerValue];
            }
            else
            {
                _orderStatus = [_detailInfoModel.examineStatus integerValue];
            }
            
            if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId])//选择核销标准
            {
                _isNeedHXBZ = _orderStatus == SAQueryStatusToAudit?YES:NO;
            }
     
                if (_moduleType == HomeModuleTypePA) {
                    _isShowHXBZ = result[@"kwDisplayApplication"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwDisplayApplication"][@"mbContent"]?result[@"kwDisplayApplication"][@"mbContent"]:@"";
                }else
                {
                    _isShowHXBZ = result[@"kwDisplayExamine"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwDisplayExamine"][@"mbContent"]?result[@"kwDisplayExamine"][@"mbContent"]:@"";
                }
            
            
            
            dispatch_semaphore_signal(semaphore);
        } else {
            [SVProgressHUD showErrorWithStatus:message];
            dispatch_semaphore_signal(semaphore);
        }
    }];
    
}

- (void)reloadData {
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    if (_moduleType == HomeModuleTypePA)
    {
        [request startRequestProductApplyDetailWithId:_orderId];
    }
    else
    {
        [request startRequestProductCheckDetailWithId:_orderId];
    }
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            //这里做数据解析
            PDDetailModel *model = [[PDDetailModel alloc] initWithDictionary:result error:nil];
            if (_moduleType == HomeModuleTypePA)
            {
                //                _detailInfoModel = [[ProductDisplayListModel alloc] initWithDictionary:result[@"kwDisplayApplication"] error:nil];
                _detailInfoModel = model.kwDisplayApplication;
            }
            else
            {
                _detailInfoModel = [[ProductDisplayListModel alloc] initWithDictionary:result[@"kwDisplayExamine"] error:nil];
            }
            self.recordListArr = model.recordList;
            _cargoListArr = [SADetailCargoModel arrayOfModelsFromDictionaries:model.itemList];

            _detailInfoArr = @[
                               @[
                                   @{@"陈列活动名称":[ToolViewViewController GetDataStr:_detailInfoModel.name]},
                                   @{@"促销目的":[ToolViewViewController GetDataStr:_detailInfoModel.objective]},
                                   @{@"执行城市":[ToolViewViewController GetDataStr:_detailInfoModel.city]},
                                   @{@"执行范围":[ToolViewViewController GetDataStr:_detailInfoModel.ranges]},
                                   @{@"执行时间":[ToolViewViewController GetDataStr:_detailInfoModel.executionTime]},
                                   @{@"销售额":[ToolViewViewController GetDataStr:_detailInfoModel.salesVolume]},
                                   @{@"费效比率":[ToolViewViewController GetDataStr:_detailInfoModel.ratio]},
                                   @{@"期间销售额" : [ToolViewViewController GetDataStr:_detailInfoModel.activitySales]},
                                   @{@"期间费效比率" :[ToolViewViewController GetDataStr:_detailInfoModel.activityRatio]}
                                   ],
                               @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.shelfNumber]},
                                   @{@"面积": [ToolViewViewController GetDataStr:_detailInfoModel.shelfArea]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.shelfDescription]},
                                   @{@"费用预算":  [ToolViewViewController GetDataStr:_detailInfoModel.shelfBudget]}
                                   ],
                               @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.stackingNumber]},
                                   @{@"形式": [ToolViewViewController GetDataStr:_detailInfoModel.stackingForm]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.stackingArea]},
                                   @{@"费用预算": [ToolViewViewController GetDataStr:_detailInfoModel.stackingBudget]}
                                   ],
                               @[
                                   @{@"数量": [ToolViewViewController GetDataStr:_detailInfoModel.otherNumber]},
                                   @{@"形式": [ToolViewViewController GetDataStr:_detailInfoModel.otherForm]},
                                   @{@"位置说明": [ToolViewViewController GetDataStr:_detailInfoModel.otherArea]},
                                   @{@"费用预算": [ToolViewViewController GetDataStr:_detailInfoModel.otherBudget]}
                                   ]                               ];

            if (_moduleType == HomeModuleTypePA)
            {
                _orderStatus = [_detailInfoModel.approvalStatus integerValue];
            }
            else
            {
                _orderStatus = [_detailInfoModel.examineStatus integerValue];
            }
            

            
            if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId] && _moduleType == HomeModuleTypePA)//选择核销标准
            {
                _isNeedHXBZ = _orderStatus == SAQueryStatusToAudit?YES:NO;
            }
        
                if (_moduleType == HomeModuleTypePA) {
                    _isShowHXBZ = result[@"kwDisplayApplication"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwDisplayApplication"][@"mbContent"]?result[@"kwDisplayApplication"][@"mbContent"]:@"";
                }else
                {
                    _isShowHXBZ = result[@"kwDisplayExamine"][@"mbContent"]?YES:NO;
                    _mbContect = result[@"kwDisplayExamine"][@"mbContent"]?result[@"kwDisplayExamine"][@"mbContent"]:@"";
                }
            
            


            
            
            [self.tabView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

- (void)startRequestPic
{
    NSArray *picTypeArr;
    if (_moduleType == HomeModuleTypePA)
    {
        picTypeArr = @[@(PicTypeProductApply_SuperMarketDtail)];
    }
    else
    {
        picTypeArr = @[@(PicTypeProductCheck_SuperMarketDtail),@(PicTypeProductCheck_Product),@(PicTypeProductCheck_Bill)];
    }
    
    if (!_picsDic)
    {
        _picsDic = [NSMutableDictionary dictionary];
    }
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];

    [picTypeArr enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop) {

        [picRequest startRequestQueryPicWithProcessId:_orderId pageNo:@"1" pageSize:@"50" type:[obj stringValue]];
        [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
            if (succ)
            {
                NSMutableArray<PicListModel *> *tempArr = [NSMutableArray array];
                NSString *picType;
                PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
                if ([pageModel.count integerValue] > 0)
                {
                    tempArr = pageModel.list.mutableCopy;
                    picType = tempArr.firstObject.type;
                }
                //                [_picsDic setObject:tempArr forKey:[NSString stringWithFormat:@"pic%d",i]];
                [_picsDic setObject:tempArr forKey:[NSString stringWithFormat:@"pic%@", picType]];
                dispatch_semaphore_signal(semaphore);
            } else {
                [SVProgressHUD showErrorWithStatus:message];
                dispatch_semaphore_signal(semaphore);
            }
        }];
    }];
}

- (void)getData
{
    [SVProgressHUD show];
    // 创建信号量
    semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        [self startRequestTable];
    });
    
    dispatch_group_async(group, queue, ^{
        [self startRequestPic];
    });
    
    //等待4个请求完成后,创建UI
    dispatch_group_notify(group, queue, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        if (_moduleType == HomeModuleTypePC) {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        if(_isNeedHXBZ){
            [self addGetHeXiaoMessage];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setUpUI];
            });
        }
    });
}

-(void)addGetHeXiaoMessage//有权限审批 且 待审批状态
{
    //1 进场费  2 陈列费  3 促销活动
    [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/kwMoban/list",baseUrlMe] Dic:@{@"mbType":@"2"} completion:^(NSDictionary *responseDic) {
        if ([responseDic[@"success"] boolValue]){
            _DataHXBZArr = [[NSMutableArray alloc]initWithArray:responseDic[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setUpUI];
            });
        }else
        {
            [ToolViewViewController addPopAlterViewController:responseDic[@"msg"]?responseDic[@"msg"]:@"" Controller:self];
        }
    }];
}//活动目的这一项,将数字装换成中文字符
- (NSString *)getObjects
{
    NSArray *goalArr = [_detailInfoModel.objective componentsSeparatedByString:@","];
    NSMutableArray *goalStrArr = [NSMutableArray array];
    for (NSString *obj in goalArr)
    {
        if (obj.isEmptyString) {
            continue;
        }
        NSString *str = [Constants getActiviteGoalStrWithNumberStr:obj];
        [goalStrArr addObject:str];
    }
    NSString *goalsStr = [goalStrArr componentsJoinedByString:@","];
    return goalsStr;
}

//修改按钮,先判断是否是自己的订单
//如果是自己订单,待提交  待审批状态下  有修改按钮
- (void)createChangeBtn
{
    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        if ([_detailInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
        {
            if (_orderStatus == SAQueryStatusToSubmit || _orderStatus == SAQueryStatusToAudit || _orderStatus == SCQueryStatusToSubmit || _orderStatus == SCQueryStatusToAudit)
            {
                [self createRightButton:@"修改" selector:@selector(changeInfo)];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)changeInfo
{
    PDCommitVC *vc = [[PDCommitVC alloc] init];
    vc.picDic = _picsDic;
    vc.isChangeInfo = YES;
    vc.detailInfoModel = _detailInfoModel;
    vc.cargoListArr = _cargoListArr;
    vc.orderStatus = [NSString stringWithFormat:@"%ld",(long)_orderStatus];
    vc.orderId = _orderId;
    vc.moduleType = _moduleType;
    vc.isShowHXBZ = _isShowHXBZ;
    vc.mbContect = _mbContect;
    vc.reloadBlock = ^{
        [self reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createBottomView
{
    //这里创建底部操作按钮,先要判断是否是本人的订单,如果是在判断自己的身份,显示对应按钮
    //是本人订单
    //根据订单状态来显示底部按钮
    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        if ([_detailInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
        {
            if (_moduleType == HomeModuleTypePA)
            {
                if (_orderStatus == SAQueryStatusToAudit || _orderStatus == SAQueryStatusToSubmit)
                {
                    [self createBottomBtnWithTitle:@"删除"];
                }
                else if (_orderStatus == SAQueryStatusCompleted)
                {
                    [self createBottomBtnWithTitle:@"确认查看"];
                }
                else
                {
                    [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.equalTo(@0);
                    }];
                }
            }
            else if (_moduleType == HomeModuleTypePC) {
                if (_orderStatus == SCQueryStatusToSubmit) {
                    [self createSubmitButton];
                } else if (_orderStatus == SCQueryStatusToAudit) {
                    [self createBottomBtnWithTitle:@"删除"];
                }
                else {
                    [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.bottom.equalTo(@0);
                    }];
                }
            }
            
        }
    }
    else
    {
        if ([_detailInfoModel.approverUser isEqualToString:[Singleton shareInstance].userId])
        {
            if(_orderStatus == SAQueryStatusToAudit)
            {
                [self createDoubleBtnsView];
            }
            else if (_orderStatus == SAQueryStatusAuditting || _orderStatus == SAQueryStatusPlanningDepartment || _orderStatus == SAQueryStatusMarketingCenter)
            {
                [self createDoubleBtnsView];
            }
            else
            {
                [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(@0);
                }];
            }
        }
        else
        {
            [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(@0);
            }];
        }
    }
}

- (void)createBottomBtnWithTitle:(NSString *)title
{
    _deleteBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_deleteBtn setBackgroundColor:KwBlueColor];
    [_deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_deleteBtn setTitle:title forState:UIControlStateNormal];
    _deleteBtn.titleLabel.font = KwFont(16.0);
    [_deleteBtn addTarget:self action:@selector(deleteOrder:) forControlEvents:UIControlEventTouchUpInside];
    _deleteBtn.layer.masksToBounds = YES;
    _deleteBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:_deleteBtn];
    [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)createDoubleBtnsView
{
    //拒绝  通过
    btnsView = [[BottomDoubleBtnView alloc] init];
    btnsView.orderId = _orderId;
    btnsView.orderStatus = [NSString stringWithFormat:@"%ld",(long)_orderStatus];
    btnsView.moduleType = _moduleType;
    btnsView.mbContent = _DataHXBZArr.count>=_tagNumber+1?(_DataHXBZArr[_tagNumber][@"contents"]?_DataHXBZArr[_tagNumber][@"contents"]:@""):@"";
    [self.view addSubview:btnsView];
    [btnsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.height.equalTo(@50);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)createSubmitButton {
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(submitOrder) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)deleteOrder:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"确认查看"]) {
        [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/displayA/userConfirm",baseUrlMe] Dic:@{@"id":[ToolViewViewController isNotNullStr:_orderId]?_orderId:@"",@"approvalStatus":@"6"} completion:^(NSDictionary *responseDic) {
            if ([responseDic[@"success"] boolValue]) {
                [_deleteBtn removeFromSuperview];
                [self getData];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"确认失败"];
            }
            
        }];
    }else
    {
        _deleteAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_deleteAlert show];
    }
   
}

- (void)submitOrder {
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    [request startRequestPassApplyOrCheckWithId:_orderId userId:[Singleton shareInstance].userId approvalStatus:[NSString stringWithFormat:@"%zd", _orderStatus] approvalType:@"0" approvalMemo:@"" moduleType:_moduleType MbContent:_mbContect?_mbContect:@""];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ) {
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == _deleteAlert)
    {
        if (buttonIndex == 1)
        {
            NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
            [request startRequestDeleteApplyOrCheckWithId:_orderId moduleType:_moduleType];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
    }
}

- (void)setUpUI
{
    [self createChangeBtn];
    
    //创建列表
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];
    
    [self createBottomView];
    [self.tabView reloadData];
    [SVProgressHUD dismiss];
}

#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_moduleType == HomeModuleTypePA)
    {
        if (_isNeedHXBZ || _isShowHXBZ) {//展示或选择核销标准
            return 7;
        }
        return 6;
    }
    else
    {
        if (_isNeedHXBZ || _isShowHXBZ) {//展示核销标准
            return 9;
        }
        return 8;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section <= 3)
    {
        NSArray *tempArr = _detailInfoArr[section];
        if (section == 3) {
            if (self.recordListArr.count > 0 && [_detailInfoModel.approvalType integerValue] == 1) {
                return tempArr.count + self.recordListArr.count + 2;
            } else if (self.recordListArr.count > 0) {
                return tempArr.count + self.recordListArr.count + 1;
            }
        }
        return tempArr.count;
    }
    else if(section == 4)
    {
        return _cargoListArr.count;
    }
    else if(section == 5)
    {
        return 1;
    }
    else if(section == 6 && _isNeedHXBZ)//选择核销标准
    {
        return 2;
    }
    else if(section == 6 && _isShowHXBZ && _moduleType == HomeModuleTypePA)//展示核销标准
    {
        return 1;
    }
    else if(section == 8 && _isShowHXBZ && _moduleType == HomeModuleTypePC)//展示核销标准
    {
        return 1;
    }

    else
    {
        if (_moduleType == HomeModuleTypePA)
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0.000001;
    }
    else if (section <= 4 && section > 0)
    {
        return 50;
    }
    else if(section == 6 && _isShowHXBZ && _moduleType == HomeModuleTypePA)//展示核销标准
    {
        return 50;
    }
    else if(section == 8 && _isShowHXBZ && _moduleType == HomeModuleTypePC)//展示核销标准
    {
        return 50;
    }
    else
    {
        return 0.001;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return nil;
    }
    else if(section == 1)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"专架陈列"];
        return headView;
    }
    else if(section == 2)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"堆码/包柱陈列"];
        return headView;
    }
    else if(section == 3)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"其他陈列"];
        return headView;
    }
    else if(section == 4)
    {
        UIView *headView = [self createHeaderViewWithTitle:@"产品清单"];
        return headView;
    }
    else if(section == 6 && _isShowHXBZ && _moduleType == HomeModuleTypePA)//展示核销标准
    {
        UIView *headView = [self createHeaderViewWithTitle:@"费用核销标准"];
        return headView;
    }
    else if(section == 8 && _isShowHXBZ && _moduleType == HomeModuleTypePC)//展示核销标准
    {
        UIView *headView = [self createHeaderViewWithTitle:@"费用核销标准"];
        return headView;
    }
    else
    {
        return nil;
    }
}

- (UIView *)createHeaderViewWithTitle:(NSString *)title
{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *lab = [UILabel new];
    lab.text = title;
    lab.textColor = [UIColor blackColor];
    lab.font = KwFont(15);
    [headView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView.mas_left).offset(20);
        make.top.equalTo(headView).offset(15);
        make.height.equalTo(@15);
    }];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 50, self.view.bounds.size.width, 1.5);
    lineView.backgroundColor = KwGaryColor;
    [headView addSubview:lineView];
    return headView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *doubleLabCell_ID = @"DoubleLabCell";
    static NSString *cargoCell_ID = @"CargoCell";
    static NSString *photoManageCell_ID = @"PhotoManageCell";
    if(indexPath.section <= 3)
    {
        NSArray *infoTempArr = _detailInfoArr[indexPath.section];

        if (indexPath.section == 3 && indexPath.row >= infoTempArr.count) {

            if (indexPath.row == infoTempArr.count) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SystemCell"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SystemCell"];
                }
                cell.textLabel.text = @"审批信息";
                return cell;
            }

            if (indexPath.row == infoTempArr.count + self.recordListArr.count + 1) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"refuseCell"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"refuseCell"];
                }
                cell.textLabel.text = [NSString stringWithFormat:@"拒绝原因：%@", _detailInfoModel.approvalMemo];
                cell.textLabel.numberOfLines = 0;
                cell.textLabel.font = KwFont(14);
                cell.textLabel.textColor = [UIColor grayColor];
                return cell;
            }
            
            OrderRecordTableViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"record"];
            if (!cell) {
                cell = [[OrderRecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"record"];
            }
            NSLog(@"%zd", indexPath.row);
            [cell configProductRecordCell:self.recordListArr[indexPath.row - infoTempArr.count - 1]];
            return cell;
        }
        
        DoubleLabCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:doubleLabCell_ID];
        if (!cell)
        {
            cell = [[DoubleLabCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:doubleLabCell_ID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *dic = infoTempArr[indexPath.row];
        NSString *key = [dic allKeys][0];
        cell.constStr = key;
        if ([key isEqualToString:@"促销目的"])
        {
            NSString *goalsStr = [self getObjects];
            cell.paraStr = goalsStr;
        }
        else
        {
            cell.paraStr = [dic objectForKey:key];
        }
        return cell;
    }
    else if(indexPath.section == 4)
    {
        CargoCell *cell;
        //其余为商品展示
        cell = [tableView dequeueReusableCellWithIdentifier:cargoCell_ID];
        if (!cell)
        {
            cell = [[CargoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cargoCell_ID];
        }
        if (_cargoListArr.count > 0)
        {
            cell.saCargoModel = _cargoListArr[indexPath.row];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 6 && _isNeedHXBZ &&  _moduleType == HomeModuleTypePA)
    {
        if (indexPath.row == 0) {
            ChooseViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"cellText"];
            if (!cell)
            {
                cell = [[ChooseViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText"];
            }
            [cell setUpUIWithArr:_DataHXBZArr TextStr:@"" ChooseNumber:_tagNumber];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.reloadBtnBlock = ^(NSInteger tagNumber){
                
//                float oldheight =  [ToolViewViewController heightForTextViewWithText:_DataHXBZArr[_tagNumber][@"contents"]];
                
                _tagNumber = tagNumber-100;
//                
//                float Newheight =  [ToolViewViewController heightForTextViewWithText:_DataHXBZArr[_tagNumber][@"contents"]];
//                
//                if (Newheight - oldheight > 0) {
//                    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
//                        make.top.equalTo(@0);
//                        make.left.right.equalTo(@0);
//                        make.bottom.equalTo(@(-55-(Newheight - oldheight)));
//                    }];
//                }
//                
//                NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:6];
//                [_tabView reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];
//                
//                if (Newheight - oldheight > 0) {
//                    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
//                        make.top.equalTo(@0);
//                        make.left.right.equalTo(@0);
//                        make.bottom.equalTo(@0);
//                    }];
//                }
                NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:6];
                [_tabView reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];
                
                [_tabView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:6] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                

            };
            return cell;
        }else
        {
            TextViewCell *cell;
            cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
            if (!cell)
            {
                cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
            }
            [cell setUpUIWithTextStr:_DataHXBZArr[_tagNumber][@"contents"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.reloadTextBlock = ^(UITextView *texView){
                [_DataHXBZArr[_tagNumber] setObject:texView.text forKey:@"contents"];
                btnsView.mbContent = _DataHXBZArr[_tagNumber][@"contents"];
            };
            return cell;
        }
    }
    else if(indexPath.section == 6 && _isShowHXBZ &&  _moduleType == HomeModuleTypePA)
    {
        
        TextViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
        if (!cell)
        {
            cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
        }
        [cell setUpUIWithTextStr:_mbContect];
        cell.textView.editable = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 8 && _isShowHXBZ &&  _moduleType == HomeModuleTypePC)
    {
        
        TextViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
        if (!cell)
        {
            cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
        }
        [cell setUpUIWithTextStr:_mbContect];
        cell.textView.editable = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }

    else
    {
        PhotoManageCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:photoManageCell_ID];
        if (!cell)
        {
            cell = [[PhotoManageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:photoManageCell_ID];
        }
        cell.vc = self;
        cell.orderId = _orderId;
        cell.picType = PicTypeProductApply_SuperMarketDtail;
        if (_moduleType == HomeModuleTypePA)
        {
            cell.titleLabel.text = @"超市明细照片管理";
            [cell configCell:_picsDic[@"pic3"]];
        }
        else
        {
            if (indexPath.section == 5)
            {
                cell.titleLabel.text = @"超市明细照片管理";
                [cell configCell:_picsDic[@"pic4"]];
            }
            else if (indexPath.section == 6)
            {
                cell.titleLabel.text = @"产品陈列照片管理";
                [cell configCell:_picsDic[@"pic5"]];
            }
            else
            {
                cell.titleLabel.text = @"票据照片管理";
                [cell configCell:_picsDic[@"pic6"]];
            }
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)onTapLeftBarButton {
    [Singleton shareInstance].noRefresh = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSArray *)recordListArr {
    if (!_recordListArr) {
        _recordListArr = [NSArray array];
    }
    return _recordListArr;
}
@end
